package main

import (
	"net/http"
	"os"
	"code.google.com/p/cloud9lib/restc"
	"log"
	"code.google.com/p/feedgraph/rest"
)

type Geometry struct {
	Location Location "location"
}

type Location struct {
	Lat float64
	Lng float64
}

type Place struct {
	ID string
	Name string
	Icon string
	Geometry Geometry
	Latitude float64
}

type PlacesResults struct {
	Results []Place
}

type FlatPlace struct {
	ID string
	Name string
	Icon string
	Latitude float64
	Longitude float64
}

type params struct {
	Location string "location"
	Types string "types"
	Radius string "radius"
	Key string "key"
	Sensor string "sensor"
}

const API_KEY_ENV = "GOOGLE_PLACES_API_KEY"
const PLACES_URI = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"


var apiKey = os.Getenv(API_KEY_ENV)

func nearby(lat, long, types, radius string) (places PlacesResults, err error) {

	params := params{Key:apiKey, Sensor:"false"}

	params.Location = lat + "," + long
	params.Types = types
	params.Radius = radius

	err = restc.Get(PLACES_URI, params, &places)

	return
}

func getNearbyHandler(w http.ResponseWriter, req *http.Request) {

	lat := req.FormValue("lat")
	long := req.FormValue("long")
	types := req.FormValue("types")
	radius := req.FormValue("radius")

	places, err := nearby(lat, long, types, radius)

	if err != nil {
		w.WriteHeader(400)
		log.Println(err)
		return
	}

	var results []FlatPlace

	for _, p := range places.Results {
		fp := FlatPlace{
			ID: p.ID,
			Name: p.Name,
			Icon: p.Icon,
			Latitude: p.Geometry.Location.Lat,
			Longitude: p.Geometry.Location.Lng,
		}

		results = append(results, fp)
	}

	rest.WriteObject(w, req, results)
}

func main () {

	http.HandleFunc("/nearby", getNearbyHandler)
	
	err := http.ListenAndServe(":8099", nil)

	if err != nil {

		panic(err)
	}
}
